package com.daka.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.logging.LogLevel;
import org.springframework.stereotype.Component;

import java.util.logging.Level;
import java.util.logging.Logger;

@Aspect
@Component
public class OperationInterceptor {

    Logger log = Logger.getGlobal();

    @Pointcut("execution(* com.daka.controller..*Controller.*(..))")
    public void log() {
    }
    @Around("log()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String method = proceedingJoinPoint.getSignature().getName();
        String action = proceedingJoinPoint.getTarget().getClass().getSimpleName();
        //访问计数

        log.info(String.format("Request: %s.%s  参数: %s", action, method, JSON.toJSONString((proceedingJoinPoint
                .getArgs()))));
        long before = System.currentTimeMillis();
        Object result;
        try {
            result = (Object) proceedingJoinPoint.proceed();
            log.info(String.format("Response: %s.%s  耗时: %s ms 返回: %s", action, method, System.currentTimeMillis() -
                    before, JSON.toJSONString(result)));

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.log(Level.WARNING,e.getMessage());
        }
        log.info(String.format("Response: %s.%s  耗时: %s ms 返回: %s", action, method, System.currentTimeMillis() -
                before, proceedingJoinPoint.proceed()));
        return proceedingJoinPoint.proceed();
    }
}
